# -*- encoding=utf8 -*-

__author__ = "code哥"
import random
import sys
from airtest.core.api import *
# from airtest.core.android import Android
from poco.drivers.android.uiautomation import AndroidUiautomationPoco

dev = False

if dev:
    poco = AndroidUiautomationPoco(use_airtest_input=True, screenshot_each_action=False)
    from airtest.cli.parser import cli_setup

    if not cli_setup():
        auto_setup(__file__, logdir=None, devices=[
            "Android://127.0.0.1:5037/M960BDPT226TA?cap_method=JAVACAP&&ori_method=ADBORI",
        ])
else:
    import timeout_decorator
    # M960BDPT226TA WIFI 10.0.0.26 48003
    argv1 = str(sys.argv[1])
    argv2 = str(sys.argv[2])
    argv3 = str(sys.argv[3])
    argv4 = str(sys.argv[4])

    if argv2 == 'USB':
        conn_info = 'Android://127.0.0.1:5037/{uuid}?cap_method=JAVACAP&&ori_method=ADBORI'.format(
            uuid=argv1)
        device = connect_device(conn_info)
    else:
        # WIFI模式
        conn_info = 'Android://127.0.0.1:5037/{clientIp}:{port}'.format(
            clientIp=argv3,
            port=argv4)
        print(conn_info)
        device = connect_device(conn_info)

    poco = AndroidUiautomationPoco(device, use_airtest_input=True, screenshot_each_action=False)

    logdir = "{path}/static/source_img/{fileName}/{devices}".format(
        path=os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
        fileName=str(os.path.abspath(__file__).split('/')[-1]).split('.py')[0],
        devices=argv1)
    if not os.path.exists(logdir):
        os.makedirs(logdir)
    auto_setup(__file__,
               logdir=logdir,
               devices=[conn_info, ],
               project_root="{root}".format(root=os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))


def start():
    if not dev:
        set_logdir(logdir)
        # set_current(argv1)
    # 退到桌面
    home()
    stop_app('com.songheng.eastnews')
    sleep(1)
    start_app('com.songheng.eastnews')

    home_start()


def home_start():
    sleep(15)
    uh = poco(type="android.widget.ImageView", name="com.songheng.eastnews:id/uh")
    if uh.exists():
        uh.click()
    auz = poco(type="android.widget.TextView", name="com.songheng.eastnews:id/auz")
    if auz.exists():
        auz.click()
    sleep(1)
    # uc = poco(type="android.widget.ImageView", name="com.songheng.eastnews:id/uc")
    # if uc.exists():
    #     uc.click()
    a1e = poco(type="android.widget.LinearLayout", name="com.songheng.eastnews:id/a1e")
    if a1e.exists():
        an5 = poco(type="android.widget.TextView", name="com.songheng.eastnews:id/an5")
        if an5.exists():
            an5.click()

    if poco(name="com.songheng.eastnews:id/ic").exists():
        poco(name="com.songheng.eastnews:id/ic").click()
    if poco(name="com.songheng.eastnews:id/pc").exists():
        poco(name="com.songheng.eastnews:id/pc").click()
    # 刷广告
    #     if poco(name="com.songheng.eastnews:id/abl").child("android.widget.LinearLayout").exists():
    #         poco(name="com.songheng.eastnews:id/abl").child("android.widget.LinearLayout")[0].click()
    #         details2()
    #     else:
    select = random.randint(1, 3)
    if select == 1:
        # 刷新闻
        # 点击tab
        a6b = poco(type="android.widget.TextView", name="com.songheng.eastnews:id/ar3", text="新闻")

        if poco(name="com.songheng.eastnews:id/ic").exists():
            poco(name="com.songheng.eastnews:id/ic").click()
        if a6b.exists():
            a6b.click()

            abl = poco("com.songheng.eastnews:id/abl")
            abl.swipe([0, 0.5])
            sleep(2)
            if poco(name="com.songheng.eastnews:id/a5y").exists():
                poco(name="com.songheng.eastnews:id/a5y").click()
                details()
    elif select == 2:
        # 小视频
        ab3 = poco(type="android.widget.RadioButton", name="com.songheng.eastnews:id/ab3", text="视频")
        if ab3.exists():
            ab3.click()
            # 选择小视频
            akc_list = poco(type="android.widget.LinearLayout", name="com.songheng.eastnews:id/akc").children()
            if akc_list.exists():
                for item in akc_list:
                    text = item.get_text()
                    if text == "小视频":
                        item.click()
                        sleep(1)

                        abl = poco(type="android.support.v7.widget.RecyclerView", name="com.songheng.eastnews:id/abl")
                        if abl.exists():
                            abl.swipe([0, 0.5], duration=0.25)
                            sleep(2)

                            # 点击第一个
                            st_list = poco(type="android.widget.RelativeLayout", name="com.songheng.eastnews:id/st")
                            if st_list is not None and len(st_list) > 0:
                                for item in st_list:
                                    item.click()
                                    break
                                details2()
    elif select == 3:
        # 影视
        ab3 = poco(type="android.widget.RadioButton", name="com.songheng.eastnews:id/ab3", text="视频")
        if ab3.exists():
            ab3.click()
            # 选择影视
            akc_list = poco(type="android.widget.LinearLayout", name="com.songheng.eastnews:id/akc").children()
            if akc_list.exists():
                for item in akc_list:
                    text = item.get_text()
                    if text == "影视":
                        item.click()
                        sleep(1)

                        ay3 = poco(type="android.support.v7.widget.RecyclerView", name="com.songheng.eastnews:id/ay3")
                        if ay3.exists():
                            ay3.swipe([0, 0.5], duration=0.25)
                            sleep(2)

                            # 点击一个不是广告的
                            ay3_list = poco(type="android.support.v7.widget.RecyclerView",
                                            name="com.songheng.eastnews:id/ay3").children()
                            if ay3_list.exists():
                                for item in ay3_list:
                                    ald = item.offspring("com.songheng.eastnews:id/ald", textMatches=".*广告.*")
                                    if ald.exists():
                                        continue
                                    item.click()
                                    break
                                details3()


def details():
    while True:
        loop_body()


def details2():
    while True:
        loop_body2()


def details3():
    while True:
        loop_body3()


@timeout_decorator.timeout(120)
def loop_body():
    print('loop_body......')
    if poco("com.songheng.eastnews:id/awb").exists():
        poco("com.songheng.eastnews:id/awb").click()
    if poco(type="android.widget.FrameLayout", name="com.songheng.eastnews:id/a9p").exists():
        a9p = poco(type="android.widget.FrameLayout", name="com.songheng.eastnews:id/a9p")

        while True:
            if poco("com.songheng.eastnews:id/awb").exists():
                poco("com.songheng.eastnews:id/awb").click()
            a9p.swipe([0, -0.7], duration=3)
            if poco("com.songheng.eastnews:id/awb").exists():
                poco("com.songheng.eastnews:id/awb").click()
            if poco(type="android.widget.TextView", text="点击阅读全文").exists():
                poco(type="android.widget.TextView", text="点击阅读全文").click()
            if poco(type="android.widget.RelativeLayout", name="com.songheng.eastnews:id/a5z").exists():
                poco(type="android.widget.RelativeLayout", name="com.songheng.eastnews:id/a5z").click()
                break


@timeout_decorator.timeout(120)
def loop_body2():
    print('loop_body2......')
    af1 = poco(type="android.widget.RelativeLayout", name="com.songheng.eastnews:id/af1")
    a0f = poco(type="android.widget.LinearLayout", name="com.songheng.eastnews:id/a0f")
    arw = poco(type="android.widget.TextView", name="com.songheng.eastnews:id/arw", text="开始下载")
    if poco("com.songheng.eastnews:id/awb").exists():
        poco("com.songheng.eastnews:id/awb").click()
    if af1.exists():
        sleep(1)
        if not arw.exists():
            sleep(random.randint(3, 5))
        a0f.swipe([0, -0.9], duration=0.25)
    else:
        a0f.swipe([0, -0.9], duration=0.25)


@timeout_decorator.timeout(180)
def loop_body3():
    print('loop_body3......')
    sleep(1)
    # 关闭广告
    aml = poco(type="android.widget.TextView", name="com.songheng.eastnews:id/aml", textMatches=".*广告.*")
    if aml.exists():
        aml.click()
    axx = poco(type="android.widget.ListView", name="com.songheng.eastnews:id/axx")
    sleep(random.randint(10, 20))
    if poco("com.songheng.eastnews:id/awb").exists():
        poco("com.songheng.eastnews:id/awb").click()
    uf = poco(type="android.widget.ImageView", name="com.songheng.eastnews:id/uf")
    if uf.exists():
        uf.click()
    if axx.exists():
        axx.swipe([0, -0.5], duration=0.25)
        sleep(1)
        axx_list = axx.children()
        if axx_list.exists():
            for item in axx_list:
                apy = item.offspring("com.songheng.eastnews:id/x9")
                if apy.exists():
                    item.click()
                    break


def main():
    try:
        start()
    except Exception as e:
        print(e)


if __name__ == '__main__':
    main()
